//
//  Zilla.m
//  Zilla
//
//  Created by Fanty on 13-12-26.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "Zilla.h"
#import "ZillaAccessData.h"
#import "ZillaUrlScheme.h"
#import "AsyncRequestWorkGroup.h"
#import "ChamleonFormDataRequest.h"
#import "JSONParser.h"
#import "Modules.h"


@interface Zilla()

@property(nonatomic,strong) AsyncRequestWorkGroup* checkAppVaildateTask;
@property(nonatomic,strong) AsyncRequestWorkGroup* checkAppVersionTask;
@property(nonatomic,strong) AsyncRequestWorkGroup* moduleTask;

//建立带参数的post 请求
-(ChamleonFormDataRequest*)requestWithURL:(NSURL*)url;

@end

@implementation Zilla{
}

@synthesize zillAccessData;
@synthesize zillaUrlScheme;

-(id)initWithZillAccessData:(ZillaAccessData*)_zillAccessData{
    self=[super init];
    if(self){
        zillAccessData=_zillAccessData;
        zillaUrlScheme=[[ZillaUrlScheme alloc] init];
        zillaUrlScheme.zillaAccessData=zillAccessData;
    }
    return self;
}

-(id)initWithAppKey:(NSString*)_appKey appSecret:(NSString*)_appSecret urlSchemeSuffix:(NSString*)_urlSchemeSuffix{
    self=[super init];
    if(self){
        zillAccessData=[[ZillaAccessData alloc] init];
        zillAccessData.appKey=_appKey;
        zillAccessData.appSecret=_appSecret;
        zillAccessData.urlSchemeSuffix=_urlSchemeSuffix;
        zillaUrlScheme=[[ZillaUrlScheme alloc] init];
        zillaUrlScheme.zillaAccessData=zillAccessData;
    }
    return self;
}

- (void)dealloc{
    self.delegate=nil;
    [self cancelAllWorkGroup];
}

-(void)cancelAllWorkGroup{
    [self cancelCheckAppValidate];
    [self cancelCheckAppVersion];
    [self cancelSyncModules];

}

-(void)cancelCheckAppValidate{
    [self.checkAppVaildateTask cancel];
    self.checkAppVaildateTask=nil;
}

-(void)cancelCheckAppVersion{
    [self.checkAppVersionTask cancel];
    self.checkAppVersionTask=nil;

}
-(void)cancelSyncModules{
    [self.moduleTask cancel];
    self.moduleTask=nil;
}

-(ChamleonFormDataRequest*)requestWithURL:(NSURL*)url{
    ChamleonFormDataRequest* request=[ChamleonFormDataRequest requestWithURL:url];
    [request setPostValue:zillAccessData.appKey forKey:@"appKey"];
    [request setPostValue:[[NSBundle mainBundle] bundleIdentifier] forKey:@"appId"];
    [request setPostValue:zillAccessData.appToken forKey:@"token"];
    request.timeOutSeconds=10.0f;
    request.persistentConnectionTimeoutSeconds=10.0f;
    return request;
}


-(void)checkAppVaildate{
    [self cancelCheckAppValidate];
    ChamleonFormDataRequest* request=[ChamleonFormDataRequest requestWithURL:[zillaUrlScheme appCheckClient]];
    request.requestMethod=@"POST";
    [request setPostValue:self.zillAccessData.appKey forKey:@"app_key"];
    [request setPostValue:self.zillAccessData.appSecret forKey:@"app_secret"];
    
    self.checkAppVaildateTask=[[AsyncRequestWorkGroup alloc] init];
    self.checkAppVaildateTask.request=request;
    JSONParser* parser=[[JSONParser alloc] init];
    parser.serialModelName=@"AppValidate";
    self.checkAppVaildateTask.parser=parser;
    [self.checkAppVaildateTask start];

    
    
    __block AsyncRequestWorkGroup* __task=self.checkAppVaildateTask;
    __block Zilla* objSelf=self;
    __block ZillaAccessData* __zillaAccessData=zillAccessData;
    [self.checkAppVaildateTask setFinishBlock:^{
        objSelf.checkAppVaildateTask=nil;
        if([__task result]!=nil){
            AppValidate* validate=[__task result];
            __zillaAccessData.appToken=validate.token;
//            __zillaAccessData.appTokeExpired=validate.expired;
            if([objSelf.delegate respondsToSelector:@selector(authorSuccess)])
                [objSelf.delegate authorSuccess];
        }
        else{
            if([objSelf.delegate respondsToSelector:@selector(authorFailed:errorMessage:)])
                [objSelf.delegate authorFailed:[__task statusCode] errorMessage:[__task errorMessage]];
        }
    }];
}

-(void)checkAppVersion{
    [self.checkAppVersionTask cancel];
    
    self.checkAppVersionTask=[self checkAppVersionWithWorkGroup];

    
    __block AsyncRequestWorkGroup* __task=self.checkAppVersionTask;
    __block Zilla* objSelf=self;
    [self.checkAppVersionTask setFinishBlock:^{
        objSelf.checkAppVersionTask=nil;

        if([objSelf.delegate respondsToSelector:@selector(syncVersionFinish:)])
                [objSelf.delegate syncVersionFinish:[__task result]];
        
    }];
}



-(AsyncRequestWorkGroup*)syncModulesWithWorkGroup{
    ChamleonHTTPRequest *request = [ChamleonHTTPRequest requestWithURL:[zillaUrlScheme moduleListURL]];
    request.timeOutSeconds=10.0f;
    [request setPersistentConnectionTimeoutSeconds:10.0f];
    
    AsyncRequestWorkGroup* task=[[AsyncRequestWorkGroup alloc] init];
    task.request=request;
    JSONParser* parser=[[JSONParser alloc] init];
    parser.serialModelName=@"CubeModelList";
    parser.serialSubModuleName=[NSArray arrayWithObjects:@"CubeModelList",@"CubeModel", nil];
    task.parser=parser;
    [task start];
    
    
    return task;
}

-(AsyncRequestWorkGroup*)checkAppVersionWithWorkGroup{
    
    ChamleonHTTPRequest *request = [ChamleonHTTPRequest requestWithURL:[zillaUrlScheme appCheckVersion]];
    request.timeOutSeconds=10.0f;
    [request setPersistentConnectionTimeoutSeconds:10.0f];
    
    AsyncRequestWorkGroup* task=[[AsyncRequestWorkGroup alloc] init];
    task.request=request;
    JSONParser* parser=[[JSONParser alloc] init];
    parser.serialModelName=@"CubeModelList";
    parser.serialSubModuleName=[NSArray arrayWithObjects:@"CubeModelList", nil];
    task.parser=parser;
    [task start];
    

    return task;
}


-(void)syncModules{
    [self cancelSyncModules];
    self.moduleTask=[self syncModulesWithWorkGroup];
    __block AsyncRequestWorkGroup* __task=self.moduleTask;
    __block Zilla* objSelf=self;
    
    [self.moduleTask setFinishBlock:^{
        objSelf.moduleTask=nil;
        if([__task result]!=nil){
            if([objSelf.delegate respondsToSelector:@selector(syncModulesSuccess:)])
            [objSelf.delegate syncModulesSuccess:[__task result]];
        }
        else{
            
            if([objSelf.delegate respondsToSelector:@selector(syncModulesFailed:errorMessage:)])
                    [objSelf.delegate syncModulesFailed:[__task statusCode] errorMessage:[__task errorMessage]];
        }
        
    }];
}

@end



